import grails.converters.JSON

class DemoController {

    def grailsUITagLibService

    def index = { }

    def testFruitDataAsJSON = {
        def a = new Expando(id: 1, description: "Apple")
        def b = new Expando(id: 2, description: "Apricot")
        def c = new Expando(id: 3, description: "Pear")
        def d = new Expando(id: 4, description: "Peach")
        def e = new Expando(id: 5, description: "Plum")

        response.setHeader("Cache-Control", "no-store")
        def itemList = [a, b, c, d, e]
        def query = params.query
        def list = (query) ?  itemList.findAll {  it.description.contains(query)   }:itemList

        def results = list.collect {
            [  id: it.id,
               description: it.description ]
        }

        def data = [ TestData: results ]
        render data as JSON
    }

    // searchable by filterBy, or queryAppend
    def testBeerDataAsJSON = {
        def a = new Expando(id: 1, description: "Ale", link:1)
        def b = new Expando(id: 2, description: "Mead", link:1)
        def c = new Expando(id: 3, description: "Pilsner", link:2)
        def d = new Expando(id: 4, description: "Lager", link:3)
        def e = new Expando(id: 5, description: "Stout", link:3)

        response.setHeader("Cache-Control", "no-store")
        def itemList = [a, b, c, d, e]
        def query = params.query
        def list = (query) ?  itemList.findAll {  it.description.contains(query)   }:itemList

        // implement search using filterBy
        if (params.filter && params.filterBy) {
            list = list.findAll {
                it."${params.filterBy}".toString() == params.filter
            }
        }

        // implement search using parameter sent from queryAppend
        if (params.link) {
            list = list.findAll {
                it.link.toString() == params.link
            }
        }

        def results = list.collect {
            [  id: it.id,
               description: it.description ]
        }

        def data = [ TestData: results ]
        render data as JSON
    }

    def sizesAsJSON = {
        def a = new Expando(id: 1, size: "Small")
        def b = new Expando(id: 2, size: "Medium-Small")
        def c = new Expando(id: 3, size: "Medium")
        def d = new Expando(id: 4, size: "Medium-Large")
        def e = new Expando(id: 5, size: "Large")

        response.setHeader("Cache-Control", "no-store")
        def itemList = [a, b, c, d, e]
        def query = params.query
        def list = (query) ?  itemList.findAll {  it.size.contains(query)   } : itemList

        def results = list.collect {
            [   id: it.id,
                size: it.size ]
        }
        def data = [ sizes: results ]
        render data as JSON
    }

    // depends on a selection made from sizesAsJSON with default param key
    def dogsAsJSON = {
        def dogs = []
        dogs << new Expando(id: 1, type: "Chihuahua", size:"Small")
        dogs << new Expando(id: 2, type: "Dachshund", size:"Small")
        dogs << new Expando(id: 3, type: "Pomeranian", size:"Small")
        dogs << new Expando(id: 4, type: "Beagle", size:"Medium-Small")
        dogs << new Expando(id: 5, type: "Shetland Sheepdog", size:"Medium-Small")
        dogs << new Expando(id: 6, type: "Wire Fox Terrier", size:"Medium-Small")
        dogs << new Expando(id: 7, type: "Azawakh", size:"Medium")
        dogs << new Expando(id: 8, type: "Bulldog", size:"Medium")
        dogs << new Expando(id: 9, type: "Basset Hound", size:"Medium")
        dogs << new Expando(id: 10, type: "Afghan Hound ", size:"Medium-Large")
        dogs << new Expando(id: 11, type: "Boxer", size:"Medium-Large")
        dogs << new Expando(id: 12, type: "Collie", size:"Medium-Large")
        dogs << new Expando(id: 13, type: "Bloodhound", size:"Large")
        dogs << new Expando(id: 14, type: "Bullmastiff", size:"Large")
        dogs << new Expando(id: 15, type: "Akita", size:"Large")
        dogs = dogs.sort { it.type }

        response.setHeader("Cache-Control", "no-store")
        def query = params.query
        def list = (query) ?  dogs.findAll {  it.type.contains(query)   } : dogs

        // implement filter by size if it is there
        if (params.dependsOnValue) {
            list = list.findAll {
                it.size == params.dependsOnValue
            }
        }

        def results = list.collect {
            [   id: it.id,
                type: it.type ]
        }
        def data = [ dogs: results ]
        render data as JSON
    }

    // depends on a selection made from sizesAsJSON, also expects a size id and a custom param key
    def dogsAsJSONUsingId = {
        def dogs = []
        dogs << new Expando(id: 1, type: "Chihuahua", size:"Small")
        dogs << new Expando(id: 2, type: "Dachshund", size:"Small")
        dogs << new Expando(id: 3, type: "Pomeranian", size:"Small")
        dogs << new Expando(id: 4, type: "Beagle", size:"Medium-Small")
        dogs << new Expando(id: 5, type: "Shetland Sheepdog", size:"Medium-Small")
        dogs << new Expando(id: 6, type: "Wire Fox Terrier", size:"Medium-Small")
        dogs << new Expando(id: 7, type: "Azawakh", size:"Medium")
        dogs << new Expando(id: 8, type: "Bulldog", size:"Medium")
        dogs << new Expando(id: 9, type: "Basset Hound", size:"Medium")
        dogs << new Expando(id: 10, type: "Afghan Hound ", size:"Medium-Large")
        dogs << new Expando(id: 11, type: "Boxer", size:"Medium-Large")
        dogs << new Expando(id: 12, type: "Collie", size:"Medium-Large")
        dogs << new Expando(id: 13, type: "Bloodhound", size:"Large")
        dogs << new Expando(id: 14, type: "Bullmastiff", size:"Large")
        dogs << new Expando(id: 15, type: "Akita", size:"Large")
        dogs = dogs.sort { it.type }

        response.setHeader("Cache-Control", "no-store")
        def query = params.query
        def list = (query) ?  dogs.findAll {  it.type.contains(query)   } : dogs

        // implement filter by size if it is there
        def sizes = [1:"Small",2:"Medium-Small",3:"Medium",4: "Medium-Large",5: "Large"]
        if (params.size) {
            def sizeString = sizes[params.size.toInteger()]
            list = list.findAll {
                it.size == sizeString
            }
        }

        def results = list.collect {
            [   id: it.id,
                type: it.type ]
        }
        def data = [ dogs: results ]
        render data as JSON
    }

    def dataTableDataAsJSON = {
        def list = []
        def demoList = Demo.list(params)
        response.setHeader("Cache-Control", "no-store")
        demoList.each {
            list << [
                    id: it.id,
                    name: it.name,
                    birthDate: grailsUITagLibService.dateToJs(it.birthDate),
                    age: it.age,
                    netWorth: it.netWorth,
                    gender: it.gender,
                    isDumb: it.isDumb,
                    favoriteColors: it.favoriteColors.split(','),
                    dataUrl: g.createLink(action: 'dataDrillDown') + "/$it.id"
            ]
        }
        def data = [
                meTotalRecs: Demo.count(),
                results: list
        ]
        render data as JSON
    }

    def dataDrillDown = {
        render(template: 'drillDown', var: 'demo', bean: Demo.get(params.id))
    }

    def nonStandardDataTableDataAsJSON = {
        def list = []
        def criteria = Demo.createCriteria()
        def maxAge = Integer.parseInt(params.maxAge)
        def demoList = criteria.list {
            lt('age', maxAge)
            order(params.sort, params.order)
        }
        def offset = Integer.parseInt(params.offset)
        def max = Integer.parseInt(params.max)
        def endRange = (offset + max -1) <= (demoList.size()-1) ? (offset + max -1) : demoList.size()-1
        def range = offset..endRange
        def result = demoList[range]
        result.each {
            list << [
                    id: it.id,
                    name: it.name,
                    birthDate: it.birthDate.toString(),
                    age: it.age,
                    gender: it.gender,
                    netWorth: it.netWorth,
                    dataUrl: g.createLink(action: 'dataDrillDown') + "/$it.id"
            ]
        }
        def data = [
                totalRecords: demoList.size(),
                myResults: list
        ]
        render data as JSON
    }

    def tabLoader = {
        render """
            <h3>From the Server!!</h3>
            <p/>This data came straight from the controller.
        """
    }

    def toolTipLoader = {
        render """
            <h3>Tool tip markup from the server!</h3>
            <p/>Here are my params: ${params}.
        """
    }

    def ajaxDialogSelectionMade = {
        render "Your selection (${params.selection_id}:${params.selection}) has been updated to the server for id ${params.id}."
    }

    def acceptForm = {
        render "These params were sent to the server: $params"
    }

    def tableChange = {
        println "table Change!"
        println params
        def demo = Demo.get(params.id)
        if (params.field == 'age') demo."$params.field" = params.newValue.toInteger()
        else if (params.field == 'birthDate') demo."$params.field" = new Date(params.newValue)
        else if (params.field == 'name' && params.newValue==''){
          response.status = response.SC_INTERNAL_SERVER_ERROR
          return;
        }
        else demo."$params.field" = params.newValue
        demo.save()
        render "success"
    }
}
